﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;

namespace VotanetWebSite.Acceso_Usuario
{
    public partial class Administracion_Votante : System.Web.UI.Page
    {
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        private readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        private readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        private readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();

        private Users GetUser()
        {
            if (Session["usuario"] != null)
            {
                return Session["usuario"] as Users;
            }
            else
            {
                return Session["administrador"] as Users;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (GetUser() != null)
                {
                    LoadGrids(KEY);
                    LoadCivilStatusDDL();
                    LoadSexDDL();
                    LoadUser(GetUser());
                }
                else
                {
                    Response.RedirectPermanent("~/Login_Usuario.aspx");
                }
            }
        }

        private void LoadUser(Users user)
        {
            lblNombreUsuarioLogin.Text = user.GetFullName();
        }

        private void LoadCivilStatusDDL()
        {
            List<CivilStatus> list = GetListCivilStatus();
            if (list != null)
            {
                ddlEstadoCivil.DataSource = list;
                ddlEstadoCivil.DataTextField = "status";
                ddlEstadoCivil.DataValueField = "id";
                ddlEstadoCivil.DataBind();
            }
        }

        private void LoadSexDDL()
        {
            List<Gender> list = GetListSexs();
            if (list != null)
            {
                ddlSexo.DataSource = list;
                ddlSexo.DataTextField = "sex";
                ddlSexo.DataValueField = "id";
                ddlSexo.DataBind();
            }
        }

        private List<Group> GetListGroup()
        {
            return new VoterLogic().GetListGroupLogic(KEY);
        }

        private List<CivilStatus> GetListCivilStatus()
        {
            return new VoterLogic().GetListCivilStatusLogic(KEY);
        }

        private List<Gender> GetListSexs()
        {
            return new VoterLogic().GetListSexLogic(KEY);
        }

        private Group GetListOfGroupFromGrid()
        {

            // buscamos el grupo asociado al votante
            VoterLogic voterLogic = new VoterLogic();
            Group group = null;
            foreach (GridViewRow r in GrillaGrupos.Rows)
            {
                //posicion del control checkbox
                if ((r.Cells[2].Controls[1] as CheckBox) != null)
                {
                    if ((r.Cells[2].Controls[1] as CheckBox).Checked)
                    {
                        //posicion del campo oculto con el id del usuario
                        if ((r.Cells[0].Controls[1] as HiddenField) != null)
                        {
                            group = voterLogic.GetGroupByIdLogic(KEY, (r.Cells[0].Controls[1] as HiddenField).Value);
                            break;
                        }
                        else
                        {
                            group = null;
                            break;
                        }
                    }

                }
                else
                {
                    group = null;
                    break;
                }
            }
            return group;
        }

        private int ValidateCountGroup()
        {
            //valida si fueron checkeados grupos al ingresar votantes: debe ser marcado uno solo

            int count = 0;
            foreach (GridViewRow r in GrillaGrupos.Rows)
            {
                if ((r.Cells[2].Controls[1] as CheckBox) != null)
                {
                    if ((r.Cells[2].Controls[1] as CheckBox).Checked)
                    {
                        count++;
                    }
                }
            }

            return count;
        }

        private void LoadGrids(string llave)
        {
            LoadVoterGrid(llave);
            LoadGroupGrid(llave);
        }

        private void LoadVoterGrid(string key)
        {
            GridListaVotante.DataSource = GetListVoters(key);
            GridListaVotante.DataBind();
        }

        private void LoadVotingGrid(List<Voting> list)
        {
            GrillaGrupos.DataSource = list;
            GrillaGrupos.DataBind();
        }

        private void LoadGroupGrid(string key)
        {
            List<Group> list = new List<Group>();
            list = new VoterLogic().GetListGroupLogic(key);
            if (list != null)
            {
                GrillaGrupos.DataSource = list;
                GrillaGrupos.DataBind();
            }
            else
            {
                GrillaGrupos.Enabled = false;
                GrillaGrupos.Visible = false;

            }
        }

        protected void btnGuardar_Click(object sender, EventArgs e)
        {

            if (ValidateCountGroup() == 1)
            {
                SaveVoter();
            }
            else
            {
                Messages.Show(Page, Messages.ENTER_ONE_GROUP);
            }
        }

        protected List<Voter> GetListVoters(string llave)
        {
            return new VoterLogic().GetListVoters(llave);
        }

        protected void SaveVoter()
        {
            Voter voter = new Voter();
            VoterLogic voterLogic = new VoterLogic();
            voter.id = voterLogic.DecryptDataLogic(HiddenFieldUsuario.Value, KEY);
            voter.rut = txtRut.Text;
            voter.name = txtnombre1.Text;
            voter.middleName = txtnombre2.Text;
            voter.lastName = txtPaterno.Text;
            voter.secondLastName = txtMaterno.Text;


            DateTime date = new DateTime();
            if (DateTime.TryParse(txtfecha.Text, out date))
            {
                voter.birthDate = date;
            }
            else
            {
                voter.birthDate = new DateTime();
            }
            voter.email = txtemail.Text;
            voter.address = voterLogic.JoinStringLogic(ddlcalle.SelectedItem.Text, "", txtdireccion.Text);
            voter.smallTown = voterLogic.JoinStringLogic(ddlVilla.SelectedItem.Text, " ", txtVilla.Text);
            voter.regionId = ddlRegiones.SelectedValue as string;
            voter.communeId = ddlComunas.SelectedValue as string;
            voter.sex = ddlSexo.SelectedValue;
            voter.civilStatus = ddlEstadoCivil.SelectedValue;
            voter.UserId = (GetUser() != null) ? GetUser().id : null;
            voter.telephone = voterLogic.JoinStringLogic(ddlTelefonos.SelectedItem.Text, txtTelefono.Text);
            voter.cellPhone = voterLogic.JoinStringLogic(ddlCelulares.SelectedItem.Text, txtCelular.Text);
            voter.registrationDate = DateTime.Now;

            voter.allowVote = true;

            voter.group = GetListOfGroupFromGrid();


            if (voter.id == null)
            {
                if (voterLogic.SearchVoterByIdLogic(voter))
                {
                    //CleanForm();
                    Messages.Show(Page, Messages.RUT_EXIST);
                    btnGuardar.Enabled = true;
                }
                else
                {
                    if (voterLogic.FindVoterByEmailLogic(voter.email))
                    {
                        Messages.Show(Page, Messages.EMAIL_EXIST);
                    }
                    else
                    {
                        InsertVoter(voter, voterLogic);
                    }
                }
            }

        }

        protected void InsertVoter(Voter voter, VoterLogic voterLogic)
        {
            bool response = voterLogic.InsertVoterLogic(voter, KEY, USER_MAIL, USER_PASSWORD, MAIL_SERVER);
            if (response)
            {
                CleanForm();
                LoadVoterGrid(KEY);
                LoadGroupGrid(KEY);
                Messages.Show(Page, Messages.DATA_SAVED);
            }
            else
            {
                CleanForm();
                Messages.Show(Page, Messages.NO_DATA_SAVED);
            }
        }

        protected void CleanForm()
        {
            txtRut.Text = string.Empty;
            txtnombre1.Text = string.Empty;
            txtnombre2.Text = string.Empty;
            txtPaterno.Text = string.Empty;
            txtMaterno.Text = string.Empty;
            txtfecha.Text = string.Empty;
            txtemail.Text = string.Empty;
            txtdireccion.Text = string.Empty;
            txtVilla.Text = string.Empty;
            txtTelefono.Text = string.Empty;
            txtCelular.Text = string.Empty;
            HiddenFieldUsuario.Value = "0";
            hidIdUsuario.Value = "0";
            hidEmail.Value = "0";

            foreach (GridViewRow r in GrillaGrupos.Rows)
            {
                if ((r.Cells[2].Controls[1] as CheckBox) != null)
                {
                    (r.Cells[2].Controls[1] as CheckBox).Checked = false;
                    (r.Cells[2].Controls[1] as CheckBox).Enabled = true;
                }
            }

        }

        protected void GridListaVotante_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            GridListaVotante.PageIndex = e.NewPageIndex;
            LoadVoterGrid(KEY);
        }




        protected void BotonBuscar_Click(object sender, EventArgs e)
        {
            ImageButton button = (ImageButton)sender;
            switch (button.CommandName.ToLower())
            {
                case "rut":
                    string rut = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxRut"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByRutLogic(rut, KEY));
                    CleanForm();
                    break;

                case "nombre":
                    string name = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxNombre"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByName(name, KEY));
                    CleanForm();
                    break;

                case "apellido":
                    string lastName = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxApellido"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByLastNameLogic(lastName, KEY));
                    CleanForm();
                    break;

                case "email":
                    string email = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxEmail"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByEmailLogic(email, KEY));
                    CleanForm();
                    break;

                case "telefono":
                    string telephone = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxTelefono"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByTelephoneLogic(telephone, KEY));
                    CleanForm();

                    break;
                case "celular":
                    string cellphone = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxCelular"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByCellphoneLogic(cellphone, KEY));
                    CleanForm();
                    break;

                case "fecha":
                    string date = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$textboxFecha"];
                    if (!string.IsNullOrWhiteSpace(date))
                    {
                        ShowSearchInformation(new VoterLogic().SearchVoterByDateLogic(Convert.ToDateTime(date), KEY));
                        CleanForm();
                    }
                    else
                    {
                        ShowSearchInformation(new VoterLogic().SearchVoterByDateLogic(new DateTime(), KEY));
                        CleanForm();
                        break;
                    }

                    break;

                case "bloqueado":
                    string blocked = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaVotante$ctl01$ddlBloqueado"];
                    ShowSearchInformation(new VoterLogic().SearchVoterByBlockedLogic(blocked, KEY));
                    CleanForm();
                    break;

                default:
                    CleanForm();
                    LoadVoterGrid(KEY);

                    break;
            }
        }

        // muestra la informacion de los cuadros buscar  en la grilla lista votante
        protected void ShowSearchInformation(List<Voter> voterList)
        {
            if (voterList != null && voterList.Count > 0)
            {
                GridListaVotante.DataSource = voterList;
                GridListaVotante.DataBind();
            }
            else
            {
                Messages.Show(Page, Messages.USER_NOT_EXIST);
            }
        }

        protected void BtnCancelar_Click(object sender, EventArgs e)
        {
            CleanForm();
            LoadGroupGrid(KEY);
        }

        protected void BtnActualizar_Click(object sender, ImageClickEventArgs e)
        {
            CleanForm();
            LoadVoterGrid(KEY);
        }

        protected void BtnEnviarMail_Click(object sender, EventArgs e)
        {
            string message = txtEditorEmail.Text;

            if (!string.IsNullOrWhiteSpace(message))
            {
                VoterLogic voterLogic = new VoterLogic();
                Voter voter = voterLogic.GetVoterById(hidEmail.Value, KEY);
                if (voter != null)
                {
                    voterLogic.SendEmailLogic(voter, message, USER_MAIL, USER_PASSWORD, MAIL_SERVER, null);
                    CleanForm();
                    LoadVoterGrid(KEY);
                    Messages.Show(Page, Messages.MESSAGE_SENT);
                }
                else
                {
                    CleanForm();
                    LoadVoterGrid(KEY);
                    Messages.Show(Page, Messages.USER_NOT_EXIST);
                }
            }
            else
            {
                CleanForm();
                LoadVoterGrid(KEY);
                Messages.Show(Page, Messages.NO_MESSAGE_SENT);
            }

        }

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }



    }
}